# coding=utf-8
import logging
from datetime import datetime, timedelta, date
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, list_export_object, generate_filter
from common.order_withdraw.model import OrderWithdraw
from common.card_statistics_daily.model import CardStatisticsDaily
from common.utils import id_generator
from common.utils import exceptions as err
from common import orm
from sqlalchemy import func, Date, cast
from common.utils.types import Enum
from decimal import Decimal

_LOGGER = logging.getLogger('hydra')

@sql_wrapper
def get_cards_statistics(card_code):
    daily = CardStatisticsDaily.query.filter(CardStatisticsDaily.card_code == card_code,
                                             cast(CardStatisticsDaily.created_at, Date) == date.today()).first()
    if not daily:
        daily = CardStatisticsDaily()

    return daily

@sql_wrapper
def upsert_card_statistics(card_code, order_amount, order_status = -1, reverse = False):
    daily = CardStatisticsDaily.query.filter(CardStatisticsDaily.card_code == card_code, cast(CardStatisticsDaily.created_at, Date) == date.today()).first()

    if order_status == -1:
        if not daily:
            daily = CardStatisticsDaily()
            daily.created_at = datetime.utcnow()
            daily.card_code = card_code

        amount = Decimal(order_amount if not reverse else -order_amount)
        count = 1 if not reverse else -1
        daily.total_amount += amount
        daily.payment_amount += amount
        daily.processing_amount += amount
        daily.total_count += count
        daily.payment_count += count
        daily.processing_count += count
        daily.updated_at = datetime.utcnow()
        daily.save()
    else:
        if daily:
            daily.processing_amount -= order_amount
            daily.processing_count -= 1

            if order_status == 2: # ORDER_STATUS.SUCCESS:
                daily.auto_close_amount += order_amount
                daily.auto_close_count += 1
            elif order_status == 3: # ORDER_STATUS.MANUALSUCCESS:
                daily.manual_close_amount += order_amount
                daily.manual_close_count += 1
            elif order_status == 4: # ORDER_STATUS.INVALID:
                daily.invalid_amount += order_amount
                daily.invalid_count += 1
            daily.updated_at = datetime.utcnow()
            daily.save()
